package com.sgb.knowledgeshare.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.aliyun.recorder.AliyunRecorderCreator;
import com.aliyun.recorder.supply.AliyunIClipManager;
import com.aliyun.recorder.supply.AliyunIRecorder;
import com.aliyun.recorder.supply.RecordCallback;
import com.aliyun.svideo.sdk.external.struct.common.VideoQuality;
import com.aliyun.svideo.sdk.external.struct.encoder.VideoCodecs;
import com.aliyun.svideo.sdk.external.struct.recorder.CameraParam;
import com.aliyun.svideo.sdk.external.struct.recorder.CameraType;
import com.aliyun.svideo.sdk.external.struct.recorder.FlashType;
import com.aliyun.svideo.sdk.external.struct.recorder.MediaInfo;
import com.aliyun.svideo.sdk.external.struct.snap.AliyunSnapVideoParam;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.databinding.FragmentSharePublishBinding;
import com.sgb.knowledgeshare.utils.PageChangeSharePublicEvent;
import com.sgb.knowledgeshare.utils.RxBus;
import com.sgb.knowledgeshare.utils.ShareConstants;
import com.sgb.knowledgeshare.weight.RecordTimelineView;
import com.sgb.knowledgeshare.weight.RecordVideoView;
import com.sgb.knowledgeshare.weight.RecordVideoViewListener;
import com.sgb.knowledgeshare.weight.ShareVideoPhotoDialog;
import com.swgk.core.base.AppActivity;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ThreadUtils;
import java.io.File;

/**
 * 分享-录制视频呢
 */
public class ShareRecoedVideoActivity extends AppActivity {

    private static final int REQ_CODE = 101;

    private FragmentSharePublishBinding binding;
    private RecordVideoView recordvideoviews;
    private AliyunIRecorder recorder;
    private MediaInfo mOutputInfo;
    //编码方式
    private VideoCodecs mVideoCodec = VideoCodecs.H264_HARDWARE;
    private SurfaceView mRecorderSurfaceView;
    private AliyunIClipManager clipManager;
    private RecordTimelineView recordTimeView;
    private long recordTime;
    private String videoPath;
    private int width;
    private int height;
    private String RecoedvideoPath;
    private String from;
    private ShareVideoPhotoDialog shareVideoPhotoDialog;

    public static void start(Context context, String str) {
        Intent intent = new Intent();
        intent.setClass(context, ShareRecoedVideoActivity.class);
        intent.putExtra("from", str);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        from = getIntent().getStringExtra("from");
        binding = DataBindingUtil.setContentView(this, R.layout.fragment_share_publish);
        binding.surfaceview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        recordvideoviews =findViewById(R.id.recordvideoview);
        recordTimeView = recordvideoviews.getRecordTimeView();
        mRecorderSurfaceView = findViewById(R.id.surfaceview);
        recorder = AliyunRecorderCreator.getRecorderInstance(this);
        clipManager = recorder.getClipManager();
        //设置输出路径
        videoPath = ShareConstants.SDCardConstants.getDir(getApplicationContext()) + File.separator + System.currentTimeMillis() + "-record.mp4";
        recorder.setOutputPath(videoPath);
        recorder.setVideoQuality(VideoQuality.HD);//设置录制视频质量
        //recorder.setVideoBitrate(AliyunSnapVideoParam.RESOLUTION_720P);//设置录制视频的码率
        recorder.setVideoBitrate(AliyunSnapVideoParam.RESOLUTION_540P);//设置录制视频的码率
        //recorder.setGop(30);//设置输出视频的GOP大小
        recorder.setGop(5);//设置输出视频的GOP大小
        recorder.setCamera(CameraType.BACK);//设置设摄像头类型
        recorder.setFocusMode(CameraParam.FOCUS_MODE_CONTINUE);
        recorder.setRecordRotation(0);
        //recorder.setMute(false);//是否静音录制
        //设置录制视频输出参数
        WindowManager manager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        width = manager.getDefaultDisplay().getWidth();
        height = manager.getDefaultDisplay().getHeight();
        mOutputInfo = new MediaInfo();
        mOutputInfo.setFps(35);
        mOutputInfo.setVideoWidth(width);
        mOutputInfo.setVideoHeight(height);
        mOutputInfo.setVideoCodec(mVideoCodec);
        recorder.setMediaInfo(mOutputInfo);
        recorder.setDisplayView(mRecorderSurfaceView);
        recorder.startPreview();
        //录制视频按钮点击事件
        RecordVideoViewEvent(recordvideoviews);
        RecorderViewEvent(recorder);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (recorder != null) {
            recorder.startPreview();
            //录制视频按钮点击事件
            if (recordvideoviews != null) {
                RecordVideoViewEvent(recordvideoviews);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        //暂停录制，同步RecordClick状态，更具状态点击录制按钮是处理是否录制
        recorder.stopRecording();
        recordvideoviews.RecordClick= true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //底部弹窗，录制视频处理
        if (recorder != null) {
            recorder.destroy();
        }
    }

    // 录制视频点击事件处理
    private void RecordVideoViewEvent(RecordVideoView recordvideoviews) {
        recordvideoviews.setRecordvideoListener(new RecordVideoViewListener() {
            @Override
            public void onBackClick() {
                clipManager.deleteAllPart();
                recorder.destroy();
                finish();
                if (TextUtils.isEmpty(from)){
                    RxBus.getDefault().post(new PageChangeSharePublicEvent(0));
                }
            }

            @Override
            public void onNextClick() {
                recorder.stopRecording();
                //  结束录制，并且将录制片段视频拼接成一个视频
                recorder.finishRecording();
                int duration = clipManager.getDuration();
                if (duration>=1000*6){
                    //跳转到下个界面
                    if (RecoedvideoPath == null){
                        SharePublishActivity.start(ShareRecoedVideoActivity.this, videoPath,duration, 1,REQ_CODE);
                    }else {
                        SharePublishActivity.start(ShareRecoedVideoActivity.this, RecoedvideoPath,duration, 1,REQ_CODE);
                    }
                }else {
                    MToast.showToast(getApplicationContext(),"录制时长小于最小时长6s！");
                }

            }

            // 点击摄像头转换事件
            @Override
            public void onCameraSwitch() {
                recorder.switchCamera();//切换摄像头
            }

            @Override
            public void onReadyRecordClick(boolean isCancel) {
            }

            //闪光灯
            @Override
            public void onLightSwitch(boolean lightSwitch) {
                if (lightSwitch) {
                    recorder.setLight(FlashType.TORCH);
                } else {
                    recorder.setLight(FlashType.ON);
                }

            }

            @Override
            public void onStartRecordClick() {
                recorder.startRecording();
            }

            @Override
            public void onStopRecordClick() {
                recorder.stopRecording();
            }
            //删除某个片段
            @Override
            public void onDeleteClick(LinearLayout sharePhoto, ImageView shanchu, ImageView baocun) {
                recordTimeView.deleteLast();
                clipManager.deletePart();
                //获取总的片段数量来判断相册是否显示，片段数量==0时相册显示
                int partCount = clipManager.getPartCount();
                if (partCount<1){
                    sharePhoto.setVisibility(View.VISIBLE);
                    shanchu.setVisibility(View.GONE);
                    baocun.setVisibility(View.GONE);
                }
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        final int currentDuration = clipManager.getDuration();
                        recordvideoviews.setshareRecordTimes(DateUtils.generateTime(currentDuration));
                    }
                });
            }


            @Override
            public void onFilterEffectClick() {
            }

            // 完成录制
            @Override
            public void onCompleteRecordClick() {
                recorder.stopRecording();
                recorder.finishRecording();
                int duration = clipManager.getDuration();
                if (RecoedvideoPath == null){
                    SharePublishActivity.start(ShareRecoedVideoActivity.this, videoPath, duration,1, REQ_CODE);
                }else {
                    SharePublishActivity.start(ShareRecoedVideoActivity.this, RecoedvideoPath, duration, 1,REQ_CODE);
                }
            }

            //相册选择
            @Override
            public void onVideoPhoto() {
                shareVideoPhotoDialog = new ShareVideoPhotoDialog(ShareRecoedVideoActivity.this);
            }
        });
    }

    @Override
    public void finish() {
        if (shareVideoPhotoDialog!=null){
            shareVideoPhotoDialog.finishDialog();
        }
        super.finish();
    }

    //   视频录制的回调
    private void RecorderViewEvent(AliyunIRecorder recorder) {

        recorder.setRecordCallBack(new RecordCallback() {
            @Override
            public void onComplete(boolean b, long l) {
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        handleStopCallback(b, l);
                    }
                });

            }

            @Override
            public void onFinish(String s) {
                RecoedvideoPath = s;

            }

            @Override
            public void onProgress(long l) {
                final int currentDuration = clipManager.getDuration();
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        recordTime = 0;
                        recordTime = currentDuration + l;
                        //设置录制进度
                        if (recordTime == recordvideoviews.getMaxRecordTime()) {
                            //停止录制
                            recorder.stopRecording();
                            //调用录制完成的回调
                            recordvideoviews.setViewVisible();
                        } else if (recordTime < recordvideoviews.getMaxRecordTime()) {
                            recordTimeView.setDuration((int) l);
                            recordvideoviews.setshareRecordTimes(DateUtils.generateTime(recordTime));
                        } else {
                            recorder.stopRecording();
                        }
                    }
                });
            }

            @Override
            public void onMaxDuration() {
            }

            @Override
            public void onError(int i) {

            }

            @Override
            public void onInitReady() {

            }

            @Override
            public void onDrawReady() {

            }

            @Override
            public void onPictureBack(Bitmap bitmap) {

            }

            @Override
            public void onPictureDataBack(byte[] bytes) {

            }
        });
    }

    private void handleStopCallback(boolean b, long duration) {
        recorder.stopRecording();
        if (!b) {
            if (recordTimeView != null) {
                recordTimeView.setDuration(0);
            }
            return;
        }

        if (recordTimeView != null) {
            recordTimeView.setDuration((int) duration);
            recordTimeView.clipComplete();

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK && requestCode == REQ_CODE){
            finish();
            if (TextUtils.isEmpty(from)){
                RxBus.getDefault().post(new PageChangeSharePublicEvent(0));
            }
        }
    }
}
